"""
图片服务层
提供图片处理相关的业务逻辑
"""

import os
import logging
from typing import Dict, Any
from app.tools.image_tools import ImageTools
from app.tools.utils import get_file_size_mb

class ImageService:
    """图片服务类"""
    
    def __init__(self, upload_folder: str, output_folder: str):
        """
        初始化图片服务
        
        Args:
            upload_folder: 上传文件夹路径
            output_folder: 输出文件夹路径
        """
        self.upload_folder = upload_folder
        self.output_folder = output_folder
        self.image_tools = ImageTools()
        
    def remove_watermark_service(self, video_path: str, x: int, y: int, 
                                width: int, height: int) -> Dict[str, Any]:
        """
        去除水印服务
        
        Args:
            video_path: 视频文件路径
            x: 水印左上角x坐标
            y: 水印左上角y坐标
            width: 水印宽度
            height: 水印高度
            
        Returns:
            处理结果字典
        """
        try:
            # 获取原始文件信息
            original_size = get_file_size_mb(video_path)
            
            # 去除水印
            output_path = self.image_tools.remove_watermark(
                video_path, x, y, width, height, self.output_folder
            )
            
            # 获取输出文件信息
            output_size = get_file_size_mb(output_path)
            
            return {
                'success': True,
                'output_path': output_path,
                'original_size_mb': original_size,
                'output_size_mb': output_size,
                'watermark_area': {
                    'x': x,
                    'y': y,
                    'width': width,
                    'height': height
                },
                'message': '水印去除成功'
            }
        except Exception as e:
            logging.error(f"水印去除失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': '水印去除失败'
            }
    
    def create_gif_service(self, video_path: str, duration: int = 10, fps: int = 10) -> Dict[str, Any]:
        """
        创建GIF服务
        
        Args:
            video_path: 视频文件路径
            duration: GIF持续时间
            fps: GIF帧率
            
        Returns:
            处理结果字典
        """
        try:
            # 创建GIF
            output_path = self.image_tools.create_gif(video_path, self.output_folder, duration, fps)
            
            # 获取输出文件信息
            output_size = get_file_size_mb(output_path)
            
            return {
                'success': True,
                'output_path': output_path,
                'output_size_mb': output_size,
                'duration_seconds': duration,
                'fps': fps,
                'message': 'GIF创建成功'
            }
        except Exception as e:
            logging.error(f"GIF创建失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': 'GIF创建失败'
            } 